<template>
	<view>
		<view v-if="!hasUnionid" style="display: flex;flex-direction: column;align-items: center;margin-top: 20px;">
			<view>为了更好体验育优优测评</view>
			<button class="suggest-buy-btn" open-type="getUserInfo" @getuserinfo="getUserInfo" >
				请授权获取信息
			</button>
		</view>
		<view v-else class="container">
			<view class="top-view">
				<view class="question-title">{{title}}</view>
				<view class="question-desc">{{desc}}</view>
			</view>
		
			<view class="middle-view">
				<view class="question-content">{{content}}</view>
				<view class="question-parentAnswer">{{parentAnswer}}</view>
		
				<view style="position: relative;margin-top: 20rpx;" class="question-video">
					<video class="question-video" :src="guideVideo" :poster="guideVideoCover()" object-fit="cover"></video>
					<cover-image style="width: 8rpx;height: 8rpx;position: absolute;top: 0px;" src="../../../static/video_left_top.png"></cover-image>
					<cover-image style="width: 8rpx;height: 8rpx;position: absolute;bottom: 0px;" src="../../../static/video_left_bottom.png"></cover-image>
					<cover-image style="width: 8rpx;height: 8rpx;position: absolute;top: 0px;right: 0rpx;" src="../../../static/video_right_top.png"></cover-image>
					<cover-image style="width: 8rpx;height: 8rpx;position: absolute;bottom: 0rpx;right: 0rpx;" src="../../../static/video_right_bottom.png"></cover-image>
				</view>
		
				<view class="question-operation-guide">
					<text style="font-weight: bold;color: #000000;">操作方法：</text>{{operationGuide}}
				</view>
				<view v-if="passingCriteria" class="question-pass-criteria">
					<text style="font-weight: bold;color: #000000;">通过标准：</text>{{passingCriteria}}
				</view>
			</view>
		
			<view v-if="current !== -1" class="middle-view">
				<view class="item-title">测评道具:</view>
				<view class="tool-view" :class="abilityEntity.questions[current].tools.length<3?'tool-view-single':''">
					<view v-for="(item,index) in abilityEntity.questions[current].tools" class="tool-item" @click="previewImage(index)" :key="item.id">
						<image :src="formatImageUrl(item.imgUrl,400,320)" mode="aspectFill" class="tool-cover"></image>
						<text class="tool-name">{{item.title}}</text>
					</view>
				</view>
			</view>
			
			<view class="safe-area-view"></view>
			<view class="action">
				<view class="action-layout">
					<view class="dropdown">
						<view v-if="current !== -1" :class="{'dropdown-content-show':showOptions}" class="dropdown-content">
							<template v-for="(item, index) in abilityEntity.questions[current].options">
								<view class="dropdown-content-item" @click="optionClick(index)">{{item.optionTitle}}</view>
								<view class="dropdown-content-item-line"></view>
							</template>
							<view class="dropdown-content-bottom"></view>
						</view>
						<view @click="rightClick" class="action-yes">
							<!-- <view style="width: 36rpx;height: 36rpx;background-color: #007AFF;"></view> -->
							<image src="../../../static/assess-content-select-yes.png" style="width: 36rpx;height: 36rpx;"></image>
							<text style="margin-left: 10rpx;">通过</text>
						</view>
					</view>
					<view @click="wrongClick" class="action-no">
						<image src="../../../static/assess-content-select-no.png" style="width: 36rpx;height: 36rpx;"></image>
						<text style="margin-left: 10rpx;">不通过</text>
					</view>
				</view>
			</view>

			<view class="slde-container" :class="showSlde ? 'slde-container-hover' : ''">
				<view style="display: flex;flex-direction: row;align-items: center;">
					<view class="bubble" :class="showSlde ? 'slde-container-bubble' : ''">
						<view class="tail"></view>
						<text class="talk">
							宝宝再有{{abilityEntity.restUnpassToNextDimension}}项测试连续未通过，将进入下一个测评能区
						</text>
					</view>
					<image v-if="appId === 'wxf11d82eb1a38ad9e'" src="../../../static/assess-content-mty.png" style="width: 254rpx;height: 254rpx;"></image>
					<image v-else-if="appId === 'wxfcbfea348616744b'" src="../../../static/assess-content-mty.png" style="width: 254rpx;height: 254rpx;"></image>
					<image v-else src="../../../static/assess-content-kala.png" style="width: 254rpx;height: 254rpx;"></image>
				</view>
				<view class="safe-area-view"></view>
			</view>
		</view>
	</view>
</template>

<script>
	import utils from '../../../utils/utils.js'
	import account from '../../../utils/auth.js'
	export default {
		data() {
			return {
				recordId: '',

				abilityEntity: {},
				current: -1,

				showOptions: false,
				//显示卡拉提示
				showSlde: false,
				
				hasUnionid: true,
				appId: getApp().globalData.appid,
			}
		},
		onLoad(option) {
			console.log(option)
			this.recordId = option.recordId;
			this.isDraft = false;
			if (option.isDraft === 'true') {
				this.isDraft = true;
			}
			console.log(this.recordId)
			if (getApp().globalData.appid === 'wx8033fe9de99c902d') {
				var that = this;
				account.login(
				  function(res){
					console.log('登录成功');
					if (utils.isEmpty(res.data.user.unionid)) {
						//后台拿不到unionid;需要前端获取用户信息
						that.hasUnionid = false;
						that.sessionKey = res.data.session.sessionKey;
					} else {
						that.getNextEvaluateItem();
					}
				  },
				  function(res){
					console.log('登录失败');
					utils.showToast('登录失败');
				  }
				)
			} else {
				this.getNextEvaluateItem();
			}
		},
		onShow() {
			if (getApp().globalData.appid === 'wx8033fe9de99c902d') {
				uni.hideHomeButton();
			}
		},
		computed: {
			title() {
				if (this.current != -1) {
					return this.sectionToChinese(this.abilityEntity.dimensionCode) +
						'、' + this.abilityEntity.dimensionName;
				} else {
					return '测评纬度'
				}
			},
			desc() {
				if (this.current != -1) {
					var index = '';
					if (this.abilityEntity.questions.length > 1) {
						index = this.current + 1 + '/' + this.abilityEntity.questions.length
					}
					return '(' + this.abilityEntity.month + '月龄题目' + index + ',标号' +
						this.abilityEntity.questions[this.current].indexOnPaper + ')'
				} else {
					return ''
				}
			},
			content() {
				if (this.current != -1) {
					return this.abilityEntity.questions[this.current].title
				} else {
					return '题目'
				}
			},

			parentAnswer() {
				if (this.current != -1) {
					if (this.abilityEntity.questions[this.current].asPossibleAs) {
						return '* '+this.abilityEntity.questions[this.current].asPossibleAsTips;
					}
					if (this.abilityEntity.questions[this.current].parentAnswer) {
						return '* 可询问宝宝家长';
					}
				};
				return '';
			},

			operationGuide() {
				if (this.current != -1) {
					return this.abilityEntity.questions[this.current].operationGuide
				};
				return '';
			},

			passingCriteria() {
				if (this.current != -1) {
					return this.abilityEntity.questions[this.current].passingCriteria
				};
				return '';
			},

			guideVideo() {
				if (this.current != -1) {
					return this.abilityEntity.questions[this.current].guideVideo
				};
				return ''
			},
		},

		methods: {

			guideVideoCover() {
				var coverUrl = '';
				if (this.current != -1) {
					coverUrl = this.abilityEntity.questions[this.current].guideVideoCover
				};

				return utils.formatImageUrl(coverUrl, 640, 360)
			},

			rightClick() {
				this.$jiuaiDebounce.canDoFunction({
				    key:"rightClick",//基于此值判断是否可以操作，如两个方法传入了同样的key，则会混淆，建议传入调用此事件的方法名，简单好梳理
				    time:500,//如果传入time字段，则为定时器后，自动解除锁定状态，单位（毫秒）
				    success:()=>{//成功中调用应该操作的方法，被锁定状态不会执行此代码块内的方法
						this.showSlde = false;
						var options = this.abilityEntity.questions[this.current].options;
						console.log(options);
						if (options != null && options.length > 0) {
							this.showOptions = true;
							this.$jiuaiDebounce.releaseKey("rightClick")
						} else {
							this.next(1, -1)
						}
				    }
				})
			},

			optionClick(optionIndex) {
				this.showOptions = false;
				this.next(1, optionIndex);
			},

			wrongClick() {
				this.$jiuaiDebounce.canDoFunction({
				    key:"wrongClick",//基于此值判断是否可以操作，如两个方法传入了同样的key，则会混淆，建议传入调用此事件的方法名，简单好梳理
				    time:500,//如果传入time字段，则为定时器后，自动解除锁定状态，单位（毫秒）
				    success:()=>{//成功中调用应该操作的方法，被锁定状态不会执行此代码块内的方法
						this.showOptions = false;
						this.showSlde = false;
						this.next(0, -1)
				    }
				})
			},
			
			releaseKey() {
				this.$jiuaiDebounce.releaseKey("wrongClick");
				this.$jiuaiDebounce.releaseKey("rightClick");
			},

			next(checkType, optionIndex) {
				console.log(this.current);
				this.abilityEntity.questions[this.current].checkType = checkType;
				this.abilityEntity.questions[this.current].optionIndex = optionIndex;
				if (this.current + 1 < this.abilityEntity.questions.length) {
					if (this.abilityEntity.questions[this.current + 1].checked === null) {
						///下一题 没有做过 才显示;
						this.current += 1;
						this.releaseKey();
						return;
					} else {
						///已做过
						if (this.current + 2 < this.abilityEntity.questions.length) {
							this.current += 2;
							this.releaseKey();
							return;
						}
					}
				}
				console.log('console pass')
				var currentQuestionIds = '';
				var options = '';
				var map = new Map();
				for (var index in this.abilityEntity.questions) {
					var item = this.abilityEntity.questions[index];
					currentQuestionIds += item.id;
					currentQuestionIds += '|';

					options += item.checkType == 1 ? 'true' : 'false';
					options += '|';

					map.set(item.id, item.checkType == 1 ? true : false);

					console.log(item.optionIndex);
					if (item.optionIndex != -1) {
						for (var optionIndex in item.options) {
							var optionItem = item.options[optionIndex];
							console.log(optionItem);
							console.log(optionIndex <= item.optionIndex);
							if (optionIndex <= item.optionIndex) {
								map.set(optionItem.id, true);
							} else {
								map.set(optionItem.id, false);
							}
						}
					}
				}
				if (currentQuestionIds.length > 0) {
					currentQuestionIds = currentQuestionIds.substring(0, currentQuestionIds.length - 1);
				}
				if (options.length > 0) {
					options = options.substring(0, options.length - 1);
				}
				// console.log(currentQuestionIds);
				// console.log(options);
				// console.log(JSON.stringify(this._strMapToObj(map)));

				this.getNextEvaluateItem(currentQuestionIds, JSON.stringify(this._strMapToObj(map)));
			},

			_strMapToObj(strMap) {
				let obj = Object.create(null);
				for (let [k, v] of strMap) {
					obj[k] = v;
				}
				return obj;
			},

			getNextEvaluateItem(currentQuestionIds, options) {
				uni.showLoading({
					title: '加载...'
				})
				var qs = {
					recordId: this.recordId,
					resume: this.isDraft,
				}
				if (currentQuestionIds != null && options != null) {
					qs = {
						recordId: this.recordId,
						currentQuestionIds: currentQuestionIds,
						options: options,
						resume: false,
					}
				}
				console.log(qs);
				this.$http.post('/eapi/operator/next_evaluate_item_v2', {}, {
						params: qs,
					}).then(res => {
						this.releaseKey();
						uni.hideLoading();
						console.log(res);
						if (res.code === '000000') {
							if (res.data != null && res.data.questions != null) {
								var current = -1;
								var restUnpassToNextCount = 0;
								for (var index in res.data.questions) {
									res.data.questions[index].checkType = -1;
									res.data.questions[index].optionIndex = -1;

									if (res.data.questions[index].checked === true) {
										res.data.questions[index].checkType = 1;
										restUnpassToNextCount =+ 1;
									} else if (res.data.questions[index].checked === false) {
										res.data.questions[index].checkType = 0;
										restUnpassToNextCount =+ 1;
									} else {
										if (current === -1) {
											current = parseInt(index);
										}
									}
								}

								if (current === -1) {
									current = 0;
								}
								this.current = current;
								this.abilityEntity = res.data;
								if (res.data.restUnpassToNextDimension != null) {
									res.data.restUnpassToNextDimension = res.data.restUnpassToNextDimension - restUnpassToNextCount;
									this.showSlde = true;
								}
							} else {
								uni.redirectTo({
									url: '../assess-result/assess-result?evaluateRecordId=' + this.recordId + '&isShared=false'
								})
							}
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
					.catch(err => {
						this.releaseKey();
						uni.hideLoading();
						console.log(err);
					});
			},

			sectionToChinese(s) {
				return utils.sectionToChinese(s)
			},

			previewImage(imgCurrent) {
				var urls = new Array();
				for (var index in this.abilityEntity.questions[this.current].tools) {
					var item = this.abilityEntity.questions[this.current].tools[index];
					if (!utils.isEmpty(item.imgUrl)) {
						urls[index] = item.imgUrl;
					}
				}
				uni.previewImage({
					current: imgCurrent,
					urls: urls,
				})
			},

			formatImageUrl(imgUrl, width, height) {
				return utils.formatImageUrl(imgUrl, width, height)
			},
			
			getUserInfo(res) {
				console.log(res);
				this.getWxInfo(res.detail.encryptedData, res.detail.iv, res.detail.rawData, this.sessionKey ,res.detail.signature);
			},
			
			getWxInfo(encryptedData, iv, rawData, sessionKey, signature) {
				let that = this;
				var url = 'wx/user/' + getApp().globalData.appid + '/wxinfo';
				this.$http.request({
					url: url,
					method: 'post',
					params: {
						appid: getApp().globalData.appid,
						encryptedData: encryptedData,
						iv: iv,
						rawData: rawData,
						sessionKey: sessionKey,
						signature: signature,
					},
				}).then(res => {
					console.log(res);
					that.hasUnionid = true;
					that.getNextEvaluateItem();
				}).catch(err => {
					console.log(err);
				});
			}
		}
	}
</script>

<style lang="scss">
	uni-page-body,
	#app {
		height: 100%;
	}

	page {
		height: 100%;
		background-color: #F7F7F7;
	}

	.container {
		display: flex;
		flex-direction: column;

		position: relative;
		top: 0;

		background-color: #F7F7F7;

		padding-bottom: 140rpx;
	}

	.top-view {
		background: rgba(250, 203, 47, 1);
		opacity: 1;
		border-radius: 4px;

		display: flex;
		flex-direction: row;
		align-items: center;

		padding-left: 30rpx;
		padding-top: 30rpx;
		padding-bottom: 30rpx;
		padding-right: 30rpx;
		margin-top: 20rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		
		@include main-bg();
	}

	.question-title {
		font-size: 36rpx;
		color: #FFFFFF;
		font-weight: bold;
	}

	.question-desc {
		font-size: 24rpx;
		color: #FFFFFF;
		font-weight: bold;
		margin-left: 10rpx;
	}

	.middle-view {
		background: rgba(255, 255, 255, 1);
		opacity: 1;
		border-radius: 4px;

		display: flex;
		flex-direction: column;

		padding-left: 30rpx;
		padding-top: 30rpx;
		padding-bottom: 30rpx;
		padding-right: 30rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	.question-content {
		color: #333333;
		font-weight: bold;
		font-size: 50rpx;
		letter-spacing: 2rpx;
	}

	.question-parentAnswer {
		height: 30rpx;
		font-size: 28rpx;
		color: rgba(153, 153, 153, 1);
		opacity: 1;
	}

	.item-title {
		font-size: 36rpx;
		color: #666666;
	}

	.video-view {
		border-radius: 10px;
	}

	.question-video {
		align-self: center;
		width: 640rpx;
		height: 360rpx;
	}

	.question-operation-guide {
		margin-top: 30rpx;
		color: #333333;
		font-size: 30rpx;
	}

	.question-pass-criteria {
		margin-top: 20rpx;
		color: #333333;
		font-size: 30rpx;
	}

	.tool-scroll-view {
		white-space: nowrap;
		width: 100%;
		margin-top: 24rpx;

		// background-color: #007AFF;
	}

	.tool-view {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		// background-color: #007AFF;
	}

	.tool-view-single {
		justify-content: center;
	}

	.tool-empty {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		margin-top: 40rpx;
	}

	.tool-item {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 33.33%;
		text-align: center;
		font-size: 36rpx;
		margin-top: 20rpx;

		// background-color: #007AFF;
	}

	.tool-cover {
		width: 150rpx;
		height: 120rpx;

		border-color: #E6E6E6;
		border-width: 1px;
		border-style: solid;
	}

	.tool-name {
		color: #999999;
		font-size: 24rpx;
		margin-top: 5rpx;
	}
	.action {
		position: fixed;
		bottom: 0rpx;
		background-color: #FFFFFF;
		border: 1px solid rgba(230, 230, 230, 1);
		width: 100%;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
	.action-layout {
		width: 100%;
		height: 160rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		z-index: 2;
	}

	.action-yes {
		width: 240rpx;
		height: 100rpx;
		background: rgba(5, 202, 137, 1);
		opacity: 1;
		border-radius: 8rpx;
		font-size: 36rpx;
		color: #FFFFFF;
		font-weight: bold;

		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		z-index: 2;
		position: relative;
	}

	.action-no {
		width: 240rpx;
		height: 100rpx;
		background: rgba(250, 79, 58, 1);
		opacity: 1;
		border-radius: 8rpx;
		font-size: 36rpx;
		color: #FFFFFF;
		font-weight: bold;
		
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		z-index: 2;
		position: relative;
		
		margin-left: 80rpx;
		
		@include main-bg();
	}

	.dropdown {
		position: relative;
		display: inline-block;
	}

	.dropdown-content {
		display: none;
		position: absolute;
		bottom: 0;
		flex-direction: column;
		align-items: center;

		width: 232rpx;
		background: rgba(112, 112, 112, 1);
		opacity: 0.68;

		border-top: 4rpx solid rgba(51, 51, 51, 1);
		border-right: 4rpx solid rgba(51, 51, 51, 1);
		border-left: 4rpx solid rgba(51, 51, 51, 1);
		border-top-left-radius: 8rpx;
		border-top-right-radius: 8rpx;
		border-bottom-left-radius: 8rpx;
		border-bottom-right-radius: 8rpx;
	}

	.dropdown-content-item {
		width: 100%;
		height: 86rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #FFFFFF;
		font-size: 26rpx;
	}

	.dropdown-content-item-line {
		width: 232rpx;
		height: 4rpx;
		background: rgba(51, 51, 51, 1);
		opacity: 0.4;
	}

	.dropdown-content-bottom {
		height: 100rpx;
		width: 232rpx;
		background: rgba(112, 112, 112, 1);
		opacity: 0.68;
		border-bottom-left-radius: 8rpx;
		border-bottom-right-radius: 8rpx;
		border-right: 4rpx solid rgba(51, 51, 51, 1);
		border-left: 4rpx solid rgba(51, 51, 51, 1);
	}

	.dropdown-content-show {
		display: flex;
	}

	.slde-container {
		position: fixed;
		bottom: 160rpx;
		right: -254rpx;
		display: flex;
		flex-direction: column;
		z-index: 1;
	}

	.slde-container-hover {
		animation-name: mymove;
		animation-duration: 0.3s;
		animation-iteration-count: 1;
		animation-fill-mode: forwards;
	}

	@keyframes mymove {
		from {
			right: -254rpx;
		}

		to {
			right: -30rpx;
		}
	}

	.slde-container-bubble {
		animation-name: bubble-animation;
		animation-duration: 0.3s;
		animation-delay: 0.3s;
		animation-iteration-count: 1;
		animation-fill-mode: forwards;
	}

	@keyframes bubble-animation {
		from {
			opacity: 0;
		}

		to {
			opacity: 0.7;
		}
	}

	.bubble {
		position: relative;
		width: 400rpx;
		height: 130rpx;
		border-radius: 10rpx;
		background-color: currentColor;
		color: #707070;
		background: currentColor;
		opacity: 0;
		padding-left: 15rpx;
		padding-right: 15rpx;
	}

	.bubble .tail {
		position: absolute;
		left: 100%;
		bottom: 46rpx;
		width: 0;
		height: 0;
		border-width: 14rpx;
		border-style: solid;
		border-color: transparent;
		border-left-width: 21rpx;
		border-left-color: currentColor;
		color: #707070;
	}

	.bubble .talk {
		width: 100%;
		height: 100%;

		display: flex;
		justify-content: center;
		align-items: center;
		color: #FFFFFF;
		font-size: 24rpx;
	}
	
	.suggest-buy-btn {
		width: 201px;
		height: 50px;
		background: linear-gradient(180deg, rgba(250, 204, 48, 1) 0%, rgba(252, 222, 122, 1) 100%);
		opacity: 1;
		border-radius: 4px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 60rpx;
		color: #FFFFFF;
		font-size: 36rpx;
		font-weight: bold;
	
		@include assess-result-share-bg();
	}
</style>
